class Dep {
    constructor() {
      this.subscribers = new Set();
    }
    depend() {
      if (activeWatcher) {
        // console.log(activeWatcher,"activeWatcher");
        this.subscribers.add(activeWatcher);
      }
    }
    clear(){
      this.subscribers.clear();
    }
    notify() {
      this.subscribers.forEach(watcher => watcher.update());
    }
  }
  
  let activeWatcher = null;
  
  class Watcher {
    constructor(updateFn) {
      this.updateFn = updateFn;
      this.update();
    }
    update() {
      activeWatcher = this;
      this.updateFn();
      activeWatcher = null;
    }
  }
  
  // function defineReactive(obj, key) {
  //   let value = obj[key];
  //   const dep = new Dep();
  
  //   Object.defineProperty(obj, key, {
  //     get() {
  //       dep.depend(); // 收集依赖
  //       return value;
  //     },
  //     set(newValue) {
  //       if (newValue !== value) {
  //         value = newValue;
  //         dep.notify(); // 通知更新
  //       }
  //     },
  //   });
  // }



  // 将 data 转换为响应式
  // Object.keys(vm.data).forEach(key => defineReactive(vm.data, key));

const schemaFactoryMap = new Map();
const runTask = new Map();
class Factory {
  constructor(options,model,path){
    this.dep = new Dep();
    this.model = model;
    
    this.path = path;
    this.runTask = runTask;
    this.schemaFactoryMap = schemaFactoryMap;
    this.source = options;
    Object.assign(this,options);
    // console.log(this.props,"this.props");
    if(this.schemaFactoryMap.has(this.fieldId)){
      const arrs = this.schemaFactoryMap.get(this.fieldId);
      arrs.indexOf(this)==-1 && this.schemaFactoryMap.get(this.fieldId).push(this);
    }else{
      this.schemaFactoryMap.set(this.fieldId,[this]);
    }
    this.bindWatch();
    this.render();
    
  }
  queryField(model,path) {
		const pathAttr = path.split(".");
		const value = pathAttr.reduce((acc, bcc) => {
			try {
				return acc[bcc];
				// eslint-disable-next-line no-unused-vars
			} catch (error) {
				return void 0;
			}
		}, model);
		return value;
	}
  render(){
    const runTask =  this.runTask.get(this.fieldId);
    // runTask && runTask.forEach(item => item.notify());
    if(runTask){
      runTask.forEach(item => item.notify());
      this.runTask.delete(this.fieldId);
     }
  }
  change(value){
    console.log("数据变化执行",this.path,'value:'+value);
    // console.log(this.bind.path);
    // this.bind.model[this.bind.key] = value;
    const scopeIndex = this.schemaFactoryMap.get(this.fieldId).findIndex(item => item === this);
    console.log(scopeIndex,"change-scopeIndex");
    this.notify();
  }
  destroy(){
     console.log("组件是卸载")
     this.dep.clear();
     const selfs =  this.schemaFactoryMap.get(this.fieldId);
     const index= selfs.findIndex(item => item === this);
    //  this.schemaFactoryMap.set(this.fieldId,selfs);
     console.log(index,"卸载的index--------",selfs.length);
     index!==-1 && selfs.splice(index,1);
     if(selfs.length === 0){
       this.schemaFactoryMap.delete(this.fieldId);
     }
     console.log(this.runTask,"----",this.fieldId);
     // 卸载全局task
     const runTask =  this.runTask.get(this.fieldId);
     if(runTask){
      this.runTask.delete(this.fieldId);
     }
     if(this.runTask.size === 0){
      this.runTask.clear();  
     }
   
  
  }
  notify(){
    // console.log(this.fieldId,"this.fieldId");
    this.dep.notify();
  }
  bindWatch(){
    const self = this;
    
    this.triggers['x-display'].forEach(trigger => {
        trigger && new Watcher(() => {
         
          this.dep.depend(); // 收集依赖
          // console.log("数据变化",this.model);
          const target = self.schemaFactoryMap.get(trigger.fieldId);
          const scopeIndex = self.schemaFactoryMap.get(self.fieldId).findIndex(item => item === self);
          console.log(scopeIndex,"scopeIndex",self.fieldId);
          // console.log(target,"target");
           if(target && target.length){
            // console.log(target[scopeIndex],"-----target[scopeIndex]------");
            const patchTask = (item,value,modelValue)=>{
              if(Array.isArray(value)){
                // console.log(value,"value",modelValue);
                 value.includes(modelValue) ? (item.display !== 'visible' && (item.display = 'visible')) :  (item.display !== 'none' && (item.display = 'none'));
              }else{
                console.log(value,"value");
                // if(this.model[this.fieldId] == trigger.value){
                //   item.display = 'visible';
                //   item.display = 'none';
                // }
                // alert("123")
              }
            }
            // target.forEach((item,index)=> {
            //   // console.log(item,"item----------");
            //   //  if(this.scope.length){
            //   //   const hasScope = this.scope.find(scope => scope == item);
            //   //   hasScope && patchTask(hasScope);
            //   //   return;
            //   //  }
            //   if(scopeIndex>-1 && index == scopeIndex){
            //     console.log(item,"item----task",target.scope);
            //     // patchTask(item); // 处理当前作用域
            //     return;
            //   }
            //   //  console.log(item,"item----task",target.scope);
            //    patchTask(item);
            // });
            if(target[scopeIndex]){
              // console.log(this.bind.model,this.fieldId);
              patchTask(target[scopeIndex],trigger.value,this.queryField(this.model,this.path));
            }else{
              const hasRuntask = self.runTask.get(trigger.fieldId);
              // console.log(hasRuntask,"hasRuntask");
              hasRuntask?hasRuntask.add(self):self.runTask.set(trigger.fieldId,new Set([self]));
            }
            
           }else{
              console.log(target,"target_-不存在",trigger.fieldId);
              const hasRuntask = self.runTask.get(trigger.fieldId);
              hasRuntask?hasRuntask.add(self):self.runTask.set(trigger.fieldId,new Set([self]));
              //  console.log(this.runTask);
           }
         })
    });

    // console.log(this.schemaFactoryMap,"this.schemaFactoryMap");
    // console.log(this.runTask,"this.runTask");


    // 绑定依赖关系
    // this.filedId == "filedId_1" &&  new Watcher(() => {
    //     this.dep.depend();
    //     if(this.model.filedId_1 == 2){
    //       const target = schemaFactoryMap.get('filedId_2');
    //       if(target){
    //         target.display = 'none';
    //       }else{
    //         console.log(target,"target_-不存在","filedId_2");
    //         this.runTask.set('filedId_2',this);
    //       }
    //     }else{
    //       const target = schemaFactoryMap.get('filedId_2');
    //       if(target){
    //         target.display = 'visible';
    //       }else{
    //         console.log(target,"target_-不存在","filedId_2");
    //         this.runTask.set('filedId_2',this);
    //       }
    //     }
    // });

    // this.filedId == "filedId_1" &&  new Watcher(() => {
    //   this.dep.depend();
    //   if(this.model.filedId_1 == 3){
    //     const target = schemaFactoryMap.get('filedId_2');
    //     if(target){
    //       target.required = false;
    //     }else{
    //       console.log(target,"target_-不存在","filedId_2");
    //       this.runTask.set('filedId_2',this);
    //     }
    //   }else{
    //     const target = schemaFactoryMap.get('filedId_2');
    //     if(target){
    //       target.required = true;
    //     }else{
    //       console.log(target,"target_-不存在","filedId_2");
    //       this.runTask.set('filedId_2',this);
    //     }
    //   }
    // });

    // this.filedId == "filedId_2" &&  new Watcher(() => {
    //   // this.dep.depend();
    //   const target = schemaFactoryMap.get('filedId_1');
    //   target && target.dep.depend(); // 目标收集依赖
    //   if(this.model.filedId_1== 6){
    //     target.required = false;
    //     console.log(target,"存在执行sset");
    //   }else{
    //     target.required = true;
    //   }
    // })
   
  }
}

//  schema.forEach(option => {
//    const factory = new Factory(option);
//    schemaFactoryMap.set(factory.filedId,factory);
  
//   if(factory.filedId == "filedId_1"){
//     factory.cahnge(2);
//   }
//   factory.render();
 
// });


// schemaFactoryMap.get('filedId_1').cahnge(2);
// console.log(schemaFactoryMap,"schemaFactoryMap");

// setTimeout(() => {
//   // 派发更新
//   schemaFactoryMap.get('filedId_1').cahnge(6);
//   console.log(schemaFactoryMap,"schemaFactoryMap");
// }, 2000);


// schemaFactory.forEach(item => {
//   item.render();
//   console.log(item);
// })

window.Factory = Factory;
window.schemaFactoryMap = schemaFactoryMap;
window.runTask = runTask;


  

  
  // 测试
  //vm.data.firstName = 'Jane'; // 输出: fullName updated: Jane Doe